#include "StateMachine.h"
#include "Menu.h"
#include "Game.h"
#include "InfoScreen.h"

using namespace std;

StateMachine::StateMachine(sf::RenderWindow* window) : _is_running(true), _window(window)
{
}

StateMachine::~StateMachine()
{
	for(map<state,GameState*>::iterator it=_my_states.begin(); it!=_my_states.end(); ++it)
	{
		delete it->second;
	}
}

void StateMachine::init(){
	Menu* myMenu= new Menu(_window, this);
	_my_states[menu]=myMenu;
	_current_state=menu;
}

bool StateMachine::isRunning()
{
	return _is_running;
}

void StateMachine::changeState(state s)
{
	delete _my_states[_current_state];
	_my_states.erase(_current_state);
	if(_my_states[s]!=NULL)
	{
		_current_state=s;
	}
	else
	{
		switch(s)
		{
			case game:
				{	Game* myGame= new Game(_window, this);
					myGame->init();
					_my_states[game]=myGame;
				}
				break;
			case victory:
				{
				InfoScreen* myInfoScreen= new InfoScreen(_window, this, sf::Text("Victory !"));
				myInfoScreen->init();
				_my_states[victory]=myInfoScreen;
				}
				break;
			case gameover:
				{
				InfoScreen* myInfoScreen= new InfoScreen(_window, this, sf::Text("Game Over"));
				myInfoScreen->init();
				_my_states[gameover]=myInfoScreen;
				}
				break;
			case menu:
				init();
				break;
			default:
				break;
		}
		_current_state=s;

	}
}

GameState* StateMachine::getCurrentState()
{
	return _my_states[_current_state];
}

void StateMachine::update()
{
	_my_states[_current_state]->update();
}

void StateMachine::quit()
{
	_window->close();
}